package com.foreknow.elm.dao.impl;

import com.foreknow.elm.dao.UserDao;
import com.foreknow.elm.po.User;
import com.foreknow.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private Connection conn;
    private PreparedStatement pst;
    private ResultSet rs;

    //根据用户id密码查询   登录
    @Override
    public User query(String userId, String password) throws SQLException {
        String sql = "select * from user where userId=? and password=?";
        User users = new User();
        try {
            conn = DBUtil.getConnection();
            pst = conn.prepareStatement(sql);
            pst.setString(1,userId);
            pst.setString(2,password);
            rs = pst.executeQuery();
            while (rs.next()){
                User user = new User();
                user.setUserId(rs.getString("userId"));
                user.setPassword(rs.getString("password"));
                user.setUserName(rs.getString("userName"));
                user.setUserSex(rs.getInt("userSex"));
                user.setUserImg(rs.getString("userImg"));
                user.setDelTag(rs.getInt("delTag"));
                users = user;
            }
        }finally {
            DBUtil.close(rs,pst);
        }
        return users;
    }
//根据用户编号查询用户表返回的行数
    @Override
    public int queryrow(String userId) throws SQLException {
        int a = 0;
        String sql = "select * from user where userId=?";
        try {
            conn = DBUtil.getConnection();
            pst = conn.prepareStatement(sql);
            pst.setString(1,userId);
            rs = pst.executeQuery();
            List<String> list = new ArrayList<>();
            while (rs.next()){
                String ss = rs.getString(1);
                list.add(ss);
                a = list.size();
            }
        }finally {
            DBUtil.close(rs,pst);
        }
        return a;
    }
//向用户表中添加一条记录
    @Override
    public int uinsert(User user) throws Exception {
        int a = 0;
        String sql = "insert into user(userId,password,userName,userSex)values (?,?,?,?)";
        try {
            conn = DBUtil.getConnection();
            String id = user.getUserId();
            String word = user.getPassword();
            String name = user.getUserName();
            Integer sex = user.getUserSex();
            pst = conn.prepareStatement(sql);
            pst.setString(1,id);
            pst.setString(2,word);
            pst.setString(3,name);
            pst.setInt(4,sex);
            a = pst.executeUpdate();
//            DBUtil.commitTransaction();
        }
        finally {
            DBUtil.close(pst);
        }
        return a;
    }
}
